package com.trace.controller.report;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.trace.utils.FileUtils;
import com.trace.utils.ServletUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

@RestController
@Slf4j
public class FileController {
    @PostMapping("/upload/file")

    public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("type") String type) throws IOException {
        if (file.isEmpty()) {
            return "上传文件失败";
        }
        if (StrUtil.isEmpty(type)) {
            return "参数错误!";
        }
        String date = DateUtil.format(new Date(), "yyyy-MM-dd");
        String fileName = RandomUtil.randomNumbers(10) + "." + FileUtils.getFileExtension(file.getOriginalFilename());
        String path = StrUtil.equals(type, "pic") ? "pic" : "attachment";
        Path targetDir = Paths.get("rc-upload", path, date);
        Files.createDirectories(targetDir);
        Path targetFile = targetDir.resolve(fileName);
        file.transferTo(targetFile);
        return date + "/" + fileName;
    }


    @GetMapping("/get/pic")
    public void getFileUrl(@RequestParam("path") String path1, @RequestParam("filename") String fileName, HttpServletResponse response) throws Exception {
        Path path = Paths.get("rc-upload", "pic", path1, fileName);
        if (!path.toFile().exists()) {
            try {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("文件不存在!");
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        ServletUtils.fileStreamOut(path, response);
    }

}
